package com.oleg.bigidoc.beans;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.oleg.bigidoc.db.Connection;
import com.oleg.bigidoc.domain.Regemp;

@SuppressWarnings("serial")
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable{
 
    // Simple user database :)
	private Connection conn = new Connection();
	private EntityManager em;
    //private final List<String> users;
    
    private String username;
    private String password;
     
    private boolean loggedIn;
 
    @ManagedProperty(value="#{navigationBean}")
    private NavigationBean navigationBean;
    
    /*@SuppressWarnings("unchecked")
	public LoginBean() {  	    	
       	users = em.createNativeQuery("SELECT c.LOGIN||':'||c.PASSWORD FROM CUSTOMERS c")
       			.getResultList();    	
    }*/
    
    public String doLogin() {
        // Get every user from our sample database :)    	
//        for (String user: users) {
//            String dbUsername = user.split(":")[0];
//            String dbPassword = user.split(":")[1];
    	/*CriteriaBuilder cb = em.getCriteriaBuilder();
    	CriteriaQuery q = cb.createQuery(Registration.class);
    	Root<Registration> r = q.from(Registration.class);
    	q.select(r);
    	ParameterExpression<String> p = cb.parameter(String.class);
    	ParameterExpression<String> a = cb.parameter(String.class);
    	q.where(
    		cb.and(
    			cb.equal(r.get("population"), p),
    			cb.equal(r.get("area"), a)
    		)
    	);*/
    		em = conn.getConnection();
    	 	Query query = em.createNativeQuery("SELECT * FROM REGEMP r WHERE r.LOGIN = ? and r.PASSWORD = ?", Regemp.class);
            
    		query.setParameter(1, username);
    		query.setParameter(2, password);
    		List<Regemp> result = query.getResultList();
    		conn.Close();
            // Successful login
    		if (!result.isEmpty()){
    			/*Object[] is_active = result.get(0);
    			if(Boolean.valueOf(is_active[3].toString())){*/
    			Regemp r = result.get(0);
    			if(r.isIs_active()){
    				loggedIn = true;
                    return navigationBean.redirectToWelcome();
    			}
    			FacesMessage msg = new FacesMessage("Пользователю не предоставленны права доступа!", "ERROR MSG");
    	        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
    	        FacesContext.getCurrentInstance().addMessage(null, msg);
    	         
    	        // To to login page
    	        return navigationBean.toLogin();
    		}
            /*if (dbUsername.equals(username) && dbPassword.equals(password)) {
                loggedIn = true;
                return navigationBean.redirectToWelcome();
            }*/
//        }
     // Set login ERROR
        FacesMessage msg = new FacesMessage("Пользователь или пароль неверен!", "ERROR MSG");
        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
        FacesContext.getCurrentInstance().addMessage(null, msg);
         
        // To to login page
        return navigationBean.toLogin();
    }

    public String doLogout() {
        // Set the parameter indicating that user is logged in to false
        loggedIn = false;
         
        // Set logout message
        FacesMessage msg = new FacesMessage("Выполнен выход!", "INFO MSG");
        msg.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext.getCurrentInstance().addMessage(null, msg);
         
        return navigationBean.toLogin();
    }

    // ------------------------------
    // Getters & Setters
     
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public boolean isLoggedIn() {
        return loggedIn;
    }
 
    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }
 
    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }
}
